/**
 * create by young (young2f@outlook.com) on 2023/4/16
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');

const moment = require('moment');

module.exports = class extends base {

  /**
   * 1、创建入库记录
   * 2、更新入库单数量
   * 3、更新采购单数量
   * 4、更新库存
   * @param body
   * @returns {Promise<{result: *, status: string}>}
   */
  async createInboundLot(body) {
    console.log('createInboundLot', body);
    const {
      tenantCode,
      code,
      inboundCount = 0,
      procureShippingFee = 0,
      inboundDate,
      count = 0,
      pmLotId, lotCode
    } = body;
    const { ctx } = this;
    if (!lotCode) {
      body.lotCode = 'INT' + moment()
        .format('YYYYMMDDHHmmss');
    }
    body['lotCount'] = body.inboundCount;
    body['usedCount'] = 0;
    body['lotDate'] = body.inboundDate;
    body.procureShippingFee = procureShippingFee * (inboundCount / count);
    /**
     * 创建库存批次
     */
    delete body['_id'];
    const resultIn = await ctx.app.dbs.insert('InboundLot', body);

    /**
     * 更新采购物料批次
     */
    const result = await ctx.app.dbs.updateOne('ProcureMaterialRecord', { pmLotId }, {
      $inc: { inboundCount: inboundCount },
      inboundDate
    });

    const res2 = await ctx.app.dbs.updateOne('Material', {
      code,
      tenantCode
    }, { $inc: { storeCount: inboundCount } });
    return { status: 'ok', result };
  }

  async findInboundLotMany(body) {
    const { ctx } = this;

    const { key, tenantCode, createdTs, pmLotId, code } = body;

    const _key = key ? key : 'createdTs';
    const sort = {};
    sort[_key] = -1;
    const query = { tenantCode };
    if (createdTs && createdTs.length > 0) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    if (pmLotId) query['pmLotId'] = pmLotId;
    if (code) query['code'] = code;
    const result = await ctx.app.dbs.find('InboundLot', query, sort);
    return { status: 'ok', result };
  }

  /**
   *
   * 2、更新入库单数量
   * 3、更新采购单数量
   * 4、更新库存
   * @param body
   * @returns {Promise<{result: *, status: string}>}
   */
  async deleteInboundLot(body) {
    const { ctx } = this;
    const { tenantCode, lotCode, pmLotId, inboundCount, code } = body;
    const lot = await ctx.app.dbs.findOne('InboundLot', { lotCode, tenantCode });
    const { usedCount } = lot;
    if (usedCount && usedCount > 0) {
      throw new Error('入库批次已被订单占用！');
    }
    const resultIn = await ctx.app.dbs.deleteOne('InboundLot', { lotCode, tenantCode });

    /**
     * 更新采购物料批次
     */
    const result = await ctx.app.dbs.updateOne('ProcureMaterialRecord', { pmLotId, tenantCode }, {
      $inc: { inboundCount: -inboundCount },
    });
    const res2 = await ctx.app.dbs.updateOne('Material', {
      code,
      tenantCode
    }, { $inc: { storeCount: -inboundCount } });
    return { status: 'ok', result };
  }
};
